<?php
	
	// Tell PHP that we're using UTF-8 strings until the end of the script
	mb_internal_encoding('UTF-8');
	 
	// Tell PHP that we'll be outputting UTF-8 to the browser
	mb_http_output('UTF-8');
	
	// enable debug
	error_reporting	( E_ALL );
	
	// Mostrar los errores
	ini_set('display_errors', true);
	
	
?>

<!DOCTYPE html>
<!--[if lt IE 7]> <html class="lt-ie9 lt-ie8 lt-ie7" lang="es"> <![endif]-->
<!--[if IE 7]> <html class="lt-ie9 lt-ie8" lang="es"> <![endif]-->
<!--[if IE 8]> <html class="lt-ie9" lang="es"> <![endif]-->
<!--[if gt IE 8]><!--><html lang="es"> <!--<![endif]-->
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>Mini Calendar / Date Picker</title>
  <link rel="stylesheet" href="css/estilos_calendar.css">

  <!--[if lt IE 9]><script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <script type="text/javascript" src="js/jquery/jquery.min.js"></script>

		<script type="text/javascript">
			$(document).ready(function(){
				$("#selComboAnio").change(function(){
					$.ajax({
						url:"procesa.php",
						type: "POST",
						data:"y="+$("#selComboAnio").val(),
						success: function(data){
							//$("#modelo").html(opciones);
							alert(data);
						}
					})
				});
			});
		</script>
</head>
<body>

<?php

class Calendar
{
	var $events;

	function Calendar($date)
	{
		// Conexión a la BBDD
		$connect = mysql_connect("localhost:3306","administrador", "administrador");
		if (!$connect) {
			die(mysql_error());
		}
		mysql_select_db("administrador");
		     
		// Año actual
		define('CURRENT_YEAR', 	$date->format('Y'));
		define('CURRENT_MONTH', $date->format('m'));
		define('CURRENT_DAY', 	$date->format('d'));
		
		// Días de la semana
		define('COLUMNS', 7);
		
		// Tabla de Meses 2X6
		define('YEAR_TABLE_HORIZONTAL', 6);
		define('YEAR_TABLE_VERTICAL', 2);
		
		//echo "CURRENT_YEAR    ".CURRENT_YEAR."<BR />";
		//echo "YEAR_TABLE_HORIZONTAL    ".YEAR_TABLE_HORIZONTAL."<BR />";
		//echo "YEAR_TABLE_VERTICAL    ".YEAR_TABLE_VERTICAL."<BR />";
		
		// Array de Eventos
		$this->events = array();
		
		$this->addEvent('event 4', 10, 6, 2014);
		//$this->makeEvents( 10, 6, 2015 );
		
		// Creamos el calendario
		echo '<table>' . "\n";
		echo ' <tr>' . "\n";
		echo '  <th colspan="'.COLUMNS.'">';
		echo '    <caption class="cal-caption">Seleccione un año:';
		echo '      <SELECT disabled id="selComboAnio" NAME="selComboAnio">'; 
		
		$results = mysql_query('SELECT distinct(YEAR(STR_TO_DATE(dfec_fecha, "%Y-%m-%d"))) DFEC_FECHA from T_CALENDARIO ');
		while ($row = mysql_fetch_array($results, MYSQL_ASSOC)) {
			echo '<OPTION VALUE="ID_YEAR_'. $row["DFEC_FECHA"] . '" ';
			
			// Comprobamos el año actual
			if (CURRENT_YEAR == $row["DFEC_FECHA"]) {
				echo ' selected ';
			}
			echo ' >' . $row["DFEC_FECHA"] .'</OPTION>';
		}
		
		echo '      </SELECT>'; 
		echo '    </caption>';
		echo '  </th>' . "\n";
		echo ' </tr>' . "\n";
		echo '' . "\n";

		$mes=0;
		for ($i = 1; $i <= YEAR_TABLE_VERTICAL; $i++) {
			echo ' <tr>' . "\n";
			for ($j = 1; $j <= YEAR_TABLE_HORIZONTAL; $j++) {
				$mes+=1;
				echo '  <td>' . "\n";
				echo $this->makeCalendar($mes, CURRENT_DAY, CURRENT_MONTH, CURRENT_YEAR);
				echo '  </td>' . "\n";
			}
			echo ' </tr>' . "\n";
		}
		echo ' </table>' . "\n";
	}

	function prev_month()
	{
		return mktime(0,0,0,
				(CURRENT_MONTH == 1 ? 12 : CURRENT_MONTH - 1),
				(checkdate((CURRENT_MONTH == 1 ? 12 : CURRENT_MONTH - 1), CURRENT_DAY, (CURRENT_MONTH == 1 ? CURRENT_YEAR - 1 : CURRENT_YEAR)) ? CURRENT_DAY : 1),
				(CURRENT_MONTH == 1 ? CURRENT_YEAR - 1 : CURRENT_YEAR));
	}
	
	function next_month()
	{
		return mktime(0,0,0,
				(CURRENT_MONTH_N == 12 ? 1 : CURRENT_MONTH_N + 1),
				(checkdate((CURRENT_MONTH == 12 ? 1 : CURRENT_MONTH + 1) , CURRENT_DAY ,(CURRENT_MONTH == 12 ? CURRENT_YEAR + 1 : CURRENT_YEAR)) ? CURRENT_DAY : 1),
				(CURRENT_MONTH == 12 ? CURRENT_YEAR + 1 : CURRENT_YEAR));
	}
	
	function getEvent($day, $month, $year)
	{
		$timestamp = mktime(0, 0, 0, $month, $day, $year);
		
		$event = NULL;
		if(array_key_exists($timestamp, $this->events))
			$event = $this->events[$timestamp];
		
		//echo $event."1111<br />";
		//echo $day."<br />";
		//echo $month."<br />";
		//echo $year."<br />";
		//print_r($this->events)."<br />";
		
		return $event;
	}
	
	function addEvent($event, $day, $month, $year)
	{
		$timestamp = mktime(0, 0, 0, $month, $day, $year);
		if(array_key_exists($timestamp, $this->events))
			array_push($this->events[$timestamp], $event);
		else
			$this->events[$timestamp] = array($event);
	}
	
	function makeEvents( $day, $month, $year )
	{
		if($events = $this->getEvent($day, $month, $year))
			foreach($events as $event) echo $event.'<br />';
	}
	
	function makeCalendar( $mes, $day, $month, $year)
	{		
		// Configuración
		$NUM_OF_DAYS=date("t", mktime(0, 0, 0, $mes, 1, $year));
		$CURRENT_DAY=date('j', mktime(0, 0, 0, $mes, $day, $year));
		$CURRENT_MONTH_A=date('F',mktime(0, 0, 0, $mes, 1, $year));
		$CURRENT_MONTH_N=date('n',mktime(0, 0, 0, $mes, 1, $year));
		$START_DAY=(int) date('N', mktime(0,0,0,$CURRENT_MONTH_N,1, CURRENT_YEAR)) - 1;
		//define('PREV_MONTH', $this->prev_month());
		//define('NEXT_MONTH', $this->next_month());
		
		//echo '<td width="30"><a href="?date='.PREV_MONTH.'">&lt;&lt;</a></td>';
		//echo '<td width="30"><a href="?date='.NEXT_MONTH.'">&gt;&gt;</a></td>';
		
		$ret = '';
		$ret .= '<section class="container">' . "\n";
	    $ret .=  ' <div class="cal">' . "\n";
		$ret .=  '  <table class="cal-table">' . "\n";
		$ret .=  '   <caption class="cal-caption">'.$CURRENT_MONTH_A .'</caption>' . "\n";
		$ret .=  '   <tbody class="cal-body">' . "\n";
		
		$ret .=  '<tr>';
        $ret .=  ' <td class="cal-week"><a href="#"><b>L</b></a></td>';
        $ret .=  ' <td class="cal-week"><a href="#"><b>M</b></a></td>';
        $ret .=  ' <td class="cal-week"><a href="#"><b>X</b></a></td>';
        $ret .=  ' <td class="cal-week"><a href="#"><b>J</b></a></td>';
        $ret .=  ' <td class="cal-week"><a href="#"><b>V</b></a></td>';
        $ret .=  ' <td class="cal-weekend"><a href="#"><b>S</b></a></td>';
        $ret .=  ' <td class="cal-weekend"><a href="#"><b>D</b></a></td>';
        $ret .=  '</tr>';
		
		$ret .=  '    <tr>';
		
		// Si es enero
		if ($mes == 1) {
			$YEAR_ant=($year-1);
			$NUM_OF_DAYS_ant=date("t", mktime(0, 0, 0, 12, 1, $YEAR_ant));
			$ret .=  '&nbsp;';
		} else {
			$NUM_OF_DAYS_ant=date("t", mktime(0, 0, 0, $mes-1, 1, $year));
			$ret .=  '&nbsp;';
		}
		
		// Días del mes anterior
		for($i = ($NUM_OF_DAYS_ant-$START_DAY)+1; $i <= ($NUM_OF_DAYS_ant); $i++) {
			$ret .=  '<td class="cal-off"><a href="#">'.$i.'</a></td>';
		}
		
		$rows = 1;
		for($i = 1; $i <= $NUM_OF_DAYS; $i++)
		{
			$results = mysql_query("SELECT * FROM T_CALENDARIO WHERE DFEC_FECHA = '" . $year . "-" . str_pad($mes, 2, "0", STR_PAD_LEFT) . "-" . str_pad($i, 2, "0", STR_PAD_LEFT) . "' ");
			$row = mysql_fetch_array($results);
			
			if ($row['NCOD_TOTAL'] >= 48) { 
                $ret .=  '<td class="cal-check-green"><a target="_blank" href="images/testvelocidad_'.$year.'-'.str_pad($mes, 2, "0", STR_PAD_LEFT)."-".str_pad($i, 2, "0", STR_PAD_LEFT).'.jpg">'.$i.'</a></td>';
			} else	if (($row['NCOD_TOTAL'] > 0) && ($row['NCOD_TOTAL'] < 48)) { 
				$ret .=  '<td class="cal-check"><a target="_blank" href="images/testvelocidad_'.$year.'-'.str_pad($mes, 2, "0", STR_PAD_LEFT)."-".str_pad($i, 2, "0", STR_PAD_LEFT).'.jpg">'.$i.'</a></td>';
			} else {	
				$ret .=  '<td><a href="#">'.$i.'</a></td>';
			}
			
			if((($i + $START_DAY) % COLUMNS) == 0 && $i != $NUM_OF_DAYS) {
				$ret .=  '</tr><tr>';
				$rows++;
			}
		}
		
		// Días del mes siguiente
		for($i = 1; $i <= (COLUMNS * $rows) - ($NUM_OF_DAYS + $START_DAY); $i++) {
			$ret .=  '<td class="cal-off"><a href="#">'.$i.'</a></td>';
		}
		
		$ret .=  '</tr>';
		$ret .=  '   </tbody>' . "\n";
		$ret .=  '  </table>' . "\n";
		$ret .=  ' </div>' . "\n";
		$ret .=  '</section>' . "\n";
		
		return $ret;
	}
	
}
	// Creamos el calendario
	$cal = new Calendar( new DateTime() );
	
?>

	<section class="about">
	<p class="about-links">
	  <a href="index.php" target="_parent">Índice</a>
	  <a href="mailto:interactua.dev@gmail.com" >eMail</a>
	</p>
	<p class="about-author">&copy; 2012&ndash;2013 <a href="http://thibaut.me" target="_blank">Thibaut Courouble</a> -
	  <a href="http://www.cssflow.com/mit-license" target="_blank">Licencia</a><br>
	  Original PSD by <a href="http://dribbble.com/shots/240129-Calender" target="_blank">James McDonald</a>
	</p>
	</section>

</body>
</html>